__author__ = 'z'
#coding:utf-8
import time
import  httplib
import json
app_id = ''
app_key= ''
mode_class = 'danmu'
video_mod = 'video'
def send_danmu(message,mode,stime,size,color,user,videoid):
    params = {'message':message,
          'mode':mode,
          'stime':stime,
           'size':size,
            'color':color,
            'user':user,
            'videoid':videoid
    }
    headers = {"X-Bmob-Application-Id": app_id,
    "X-Bmob-REST-API-Key": app_key,
     "Content-Type": "application/json"}
    conn = httplib.HTTPSConnection('api.bmob.cn',443)
    conn.request('POST', '/1/classes/'+mode_class, json.dumps(params), headers)
    response = conn.getresponse();
    print response.read()
    conn.close()

def get_danmaku(videoid):
    headers = {"X-Bmob-Application-Id": app_id,
    "X-Bmob-REST-API-Key": app_key,
     "Content-Type": "application/json"
    }
    conn = httplib.HTTPSConnection('api.bmob.cn',443)
    conn.request('GET', '/1/classes/'+mode_class+'?where={"videoid":"'+videoid+'"}','{}', headers)
    response = conn.getresponse()
    res = json.loads( response.read())
    conn.close()
    res = res.get('results')
    return res

def show_danmaku(dejson):
    xmlfile = ''
    xmlfile += '<?xml version="1.0" encoding="UTF-8"?><i>\n'
    for x in dejson:
        times = str(x.get('createdAt'))
        times =  time.mktime(time.strptime(times,'%Y-%m-%d %H:%M:%S'))
        xmlfile+= '<d p="'+x.get('stime')+','+x.get('mode')+','+x.get('size')+','+x.get('color')+','+str(int(times))+'">'+x.get('message')+'</d>\n'
    xmlfile += '</i>\n'
    return xmlfile

def getVideoUrl(vid):
    headers = {"X-Bmob-Application-Id": app_id,
    "X-Bmob-REST-API-Key": app_key,
     "Content-Type": "application/json"
    }
    conn = httplib.HTTPSConnection('api.bmob.cn',443)
    conn.request('GET', '/1/classes/'+video_mod+'?where={"objectId":"'+vid+'"}','{}', headers)
    response = conn.getresponse()
    res = json.loads( response.read())
    conn.close()
    res = res.get('results')
    res = res[0].get('url')
    return res

def addVideo(url):
    params = {'url':url
    }
    headers = {"X-Bmob-Application-Id": app_id,
    "X-Bmob-REST-API-Key": app_key,
     "Content-Type": "application/json"}
    conn = httplib.HTTPSConnection('api.bmob.cn',443)
    conn.request('POST', '/1/classes/'+video_mod, json.dumps(params), headers)
    response = conn.getresponse();
    test =  response.read()
    test = json.loads(test)
    conn.close()
    return test.get("objectId")

def getAllVideo():
    headers = {"X-Bmob-Application-Id": app_id,
    "X-Bmob-REST-API-Key": app_key,
     "Content-Type": "application/json"
    }
    conn = httplib.HTTPSConnection('api.bmob.cn',443)
    conn.request('GET', '/1/classes/'+video_mod,'{}', headers)
    response = conn.getresponse()
    res = json.loads( response.read())
    conn.close()
    res = res.get('results')
    return res

